<template>
  <a-card :bordered='false'>
    <div class='card-title'>{{ $route.meta.title }}</div>
    <div class='table-operator'>
      <div class='btn'>
        <a-button v-action:add type='primary' icon='plus' @click='handleAdd'>添加客户</a-button>
        <a-upload
          v-action:import
          accept='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
          :beforeUpload='beforeUpload'
          :customRequest='onUpload'
          :showUploadList='false'
          name='iFile'
        >
          <a-button
            style='margin-left: 10px'
            :loading='uploadExcelLoading'
            v-action:import
            type='primary'
            icon='file-excel'
          >
            导入客户
          </a-button>
        </a-upload>
        <a-button
          style='margin-left: 10px'
          v-action:download_template
          icon='download'
          @click='handleDownloadTemplate'
        >
          下载导入模板
        </a-button>
        <a-button
          :disabled='selectedRowKeys.length===0'
          type='primary'
          style='margin-left: 10px'
          v-action:edit_user
          icon='edit'
          @click='showBatchEditUserModel'
        >
          批量修改所属用户
        </a-button>
      </div>
      <div class='form'>
        <div class='form-item'>
          关键词查询：
          <a-input-search
            style='width: 300px;'
            v-model='queryParam.search'
            placeholder='请输入关键词'
            @search='onSearch'
          />
        </div>
        <div class='form-item'>
          客户来源：
          <SelectPresalesSource
            v-model='queryParam.pcs_id'
            @change='handleRefresh(true)'
          />
        </div>
        <div class='form-item'>
          客户类型：
          <SelectPresalesType
            v-model='queryParam.pct_id'
            @change='handleRefresh(true)'
          />
        </div>
        <div class='form-item'>
          所属用户：
          <SelectSale
            v-model='queryParam.store_user_id'
            @change='handleRefresh(true)'
          />
        </div>
        <div class='form-item'>
          录入时间：
          <a-range-picker format='YYYY-MM-DD' v-model='queryParam.create_time' @change='handleRefresh(true)' />
        </div>
        <div class='form-item'>
          最后跟进时间：
          <a-range-picker format='YYYY-MM-DD' v-model='queryParam.last_log_time' @change='handleRefresh(true)' />
        </div>
        <div class='form-item'>
          下次跟进时间：
          <a-range-picker format='YYYY-MM-DD' v-model='queryParam.next_log_time' @change='handleRefresh(true)' />
        </div>
        <div class='form-item'>
          跟进状态：
          <a-radio-group v-model='queryParam.log_status' @change='handleRefresh(true)'>
            <a-radio-button :value='-1'>
              全部
            </a-radio-button>
            <a-radio-button :value='1'>
              今日待跟进（橘色）
            </a-radio-button>
            <a-radio-button :value='2'>
              逾期未跟进（红色）
            </a-radio-button>
          </a-radio-group>
        </div>
      </div>
    </div>

    <s-table
      ref='table'
      rowKey='pc_id'
      :loading='isLoading'
      :columns='columns'
      :data='loadData'
      :pageSize='15'
      :scroll='{x:1220}'
      :row-selection='rowSelection'
      :rowClassName='setRowClassName'
    >
      <div slot='store_user' slot-scope='text, item'>
        {{ text || '-' }} <a @click='showEditUserModel(item)' v-action:edit_user>编辑</a>
      </div>

      <div slot='source' slot-scope='text, item'>
        <a-tag v-if='item.source'>{{ item.source.source_name }}</a-tag>
        <span v-else>-</span>
      </div>
      <div slot='type' slot-scope='text, item'>
        <a-tooltip v-if='item.type' placement='top'>
          <template slot='title'>
            <span>{{ item.type.type_desc }}</span>
          </template>
          <a-tag>{{ item.type.type_name }}</a-tag>
        </a-tooltip>
        <span v-else>-</span>
      </div>
      <div slot='follow' slot-scope='text, item'>
        <div>跟进次数：{{ item.follow_up_count }}</div>
        <div>最后跟进时间：{{ item.last_log_time_text || '-' }}</div>
        <div>下次跟进时间：{{ item.next_log_time_text || '-' }}</div>
      </div>

      <div slot='other_contacts' slot-scope='text, item'>
        <div>联系人：{{ text || '-' }}</div>
        <div>联系人手机：{{ item.other_contacts_mobile || '-' }}</div>
      </div>
      <div slot='customer' slot-scope='text, item'>
        <div>客户姓名：{{ item.full_name || '-' }}</div>
        <div>身份证号：{{ item.idnumber || '-' }}</div>
        <div>公司名称：{{ item.corporate_name || '-' }}</div>
        <div>授权签约人：{{ item.signatory || '-' }}</div>
        <div>手机号码：{{ item.mobile || '-' }}</div>
        <div>客户区域：{{ item.region || '-' }}</div>
      </div>
      <div slot='illustrate' slot-scope='text, item'>
        <span v-if='!item.illustrate'>-</span>
        <a-tooltip v-else placement='top'>
          <template slot='title'>
            <span v-html='item.illustrate'></span>
          </template>
          <a>{{ item.illustrate.length <= 10 ? item.illustrate : item.illustrate.substr(0, 10) + '...' }}</a>
        </a-tooltip>
      </div>
      <div class='actions' slot='action' slot-scope='text, item'>
        <a v-action:log @click='handleShowLogMode(item)'>跟进记录</a>
        <a v-action:edit @click='handleEdit(item)'>编辑</a>
        <a v-action:delete @click='handleDelete(item)'>删除</a>
      </div>
    </s-table>
    <SaveForm ref='SaveForm' @handleSubmit='handleRefresh' />
    <log-model ref='LogModel' @handleSubmit='handleRefresh' />
    <edit-user-model ref='EditUserModel' @handleSubmit='handleRefresh' />
  </a-card>
</template>

<script>
import * as Api from '@/api/presales_customer'
import * as UploadApi from '@/api/upload'

import { debounce } from '@/utils/util'
import { SelectPresalesSource, SelectPresalesType, SelectSale, STable } from '@/components'
import store from '@/store'
import SaveForm from './modules/SaveForm.vue'
import EditUserModel from './modules/EditUserModel'
import LogModel from './LogModel/Index.vue'

const publicConfig = store.getters.publicConfig

export default {
  name: 'Index',
  components: {
    SaveForm,
    EditUserModel,
    LogModel,
    SelectSale,
    SelectPresalesSource,
    SelectPresalesType,
    STable
  },
  watch: {
    // 监听路由地址的改变
    $route: {
      immediate: true,
      handler() {
        if (this.$route.query.log_status) { // 需要监听的参数
          this.queryParam = {
            log_status: this.$route.query.log_status ? Number(this.$route.query.log_status) : -1
          }
          this.handleRefresh()
        }
      }
    }
  },
  data() {
    return {
      // 查询参数
      queryParam: {
        log_status: this.$route.query.log_status ? Number(this.$route.query.log_status) : -1
      },
      // 正在加载
      isLoading: false,
      // 表头
      columns: [
        {
          title: '客户ID',
          width: 60,
          dataIndex: 'pc_id'
        },
        {
          title: '所属用户',
          width: 120,
          dataIndex: 'store_user.real_name',
          scopedSlots: { customRender: 'store_user' }
        },
        {
          width: 300,
          title: '客户信息',
          dataIndex: 'customer',
          scopedSlots: { customRender: 'customer' }
        },
        {
          title: '客户来源',
          dataIndex: 'source',
          width: 120,
          scopedSlots: { customRender: 'source' }
        },
        {
          title: '客户类型',
          dataIndex: 'type',
          width: 90,
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '其他联系人',
          width: 200,
          dataIndex: 'other_contacts',
          scopedSlots: { customRender: 'other_contacts' }
        },
        {
          width: 200,
          title: '客户需求说明',
          dataIndex: 'illustrate',
          scopedSlots: { customRender: 'illustrate' }
        },
        {
          width: 240,
          title: '跟进信息',
          dataIndex: 'follow',
          scopedSlots: { customRender: 'follow' }
        },
        {
          width: 160,
          title: '录入时间',
          dataIndex: 'create_time'
        },
        {
          fixed: 'right',
          title: '操作',
          dataIndex: 'action',
          width: 160,
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return Api.list({ ...param, ...this.queryParam })
          .then(response => {
            return response.data.list
          })
      },

      uploadSizeLimit: 20,
      uploadExcelLoading: false,

      uploadUrl: UploadApi.excel,

      selectedRowKeys: []
    }
  },
  created() {
  },

  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },

  methods: {
    setRowClassName(record, index) {
      if (record.type && record.type.not_log == 0) {
        if (record.log_status == 1) {
          return 'bg-orange'
        } else if (record.log_status == 2) {
          return 'bg-red'
        }
      }
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 事件: 上传文件之前
    beforeUpload(file, fileList) {
      // 显示错误提示(防抖处理)
      const showErrorMsg = debounce(this.$message.error, 20)
      // 验证文件大小
      const fileSizeMb = file.size / 1024 / 1024
      if (fileSizeMb > this.uploadSizeLimit) {
        showErrorMsg(`上传的文件大小不能超出${this.uploadSizeLimit}MB`)
        return false
      }
      // 验证文件上传数量
      if (fileList.length > 1) {
        showErrorMsg('一次上传的文件数量不能超出1个')
        return false
      }
      return true
    },

    // 事件: 自定义上传
    onUpload(info) {
      this.uploadExcelLoading = true
      // 构建上传参数
      const formData = new FormData()
      formData.append('iFile', info.file)
      // 开始上传
      this.uploadUrl(formData)
        .then(({ data }) => {
          var fileId = data.fileInfo.file_id
          Api.importExcel({ fileId }).then(({ message }) => {
            this.handleRefresh()
            // this.uploadExcelLoading = false
            this.$message.success(message)
          }).finally(() => {
            this.uploadExcelLoading = false
          })
        })
    },

    handleDownloadTemplate() {
      location.href = publicConfig.HTTP + 'template/template.xlsx'
    },

    showEditUserModel(item) {
      this.$refs.EditUserModel.open(item)
    },

    showBatchEditUserModel() {
      this.$refs.EditUserModel.batchOpen(this.selectedRowKeys)
    },

    // 新增记录
    handleAdd() {
      this.$refs.SaveForm.add()
    },

    // 编辑记录
    handleEdit(item) {
      this.$refs.SaveForm.edit(item)
    },

    // 查看服务列表
    handleShowLogMode(item) {
      this.$refs.LogModel.queryParam.pc_id = item.pc_id
      this.$refs.LogModel.open(item)
    },

    // 删除记录
    handleDelete(item) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk() {
          return Api.deleted({ apiId: item['pc_id'] })
            .then(result => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally(result => modal.destroy())
        }
      })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      this.selectedRowKeys = []
      this.$refs.table.refresh(bool)
    },

    // 检索查询
    onSearch() {
      this.handleRefresh(true)
    }

  }
}
</script>
<style scoped lang='less'>
::v-deep .bg-red {
  background-color: #ee8585;
}

::v-deep .bg-orange {
  background-color: #f5cb81;

}
</style>
